import Constants from '@/utils/constants'
import Func from '@/utils/functions'

export async function downloadApp(url, type) {
    try {
        const wiating = plus.nativeUI.showWaiting('更新中0%')
        const downloader = plus.downloader.createDownload(url, {}, function (d, status) {
            plus.nativeUI.closeWaiting()
            if (status == 200) {
                installApp(d.filename, type)
            } else {
                plus.nativeUI.alert('下载失败')
            }
            plus.nativeUI.closeWaiting()
        })
        let progress = 0
        downloader.addEventListener('statechanged', task => {
            switch (task.state) {
                case 1:
                    console.log('开始下载...')
                    break
                case 2:
                    console.log('链接到服务器...')
                    break
                case 3:
                    let val = parseInt(task.downloadedSize / task.totalSize * 100) || 0
                    if (progress < val) {
                        progress = val
                    }
                    wiating.setTitle(`正在下载${progress}%`)
                    break
                case 4:
                    console.log('监听下载完成')
                    break
            }
        })
        downloader.start()
    } catch (e) {
        plus.nativeUI.closeWaiting()
        console.log(e)
        // e?.code == Constants.CLIENT_ERROR && (e.text = e.msg)
        Func.hdError(e, '下载失败')
    } finally {
    }
}

export async function installApp(url, type) {
    plus.nativeUI.showWaiting('安装文件...')
    plus.runtime.install(
        url, { force: true },
        function () {
            plus.nativeUI.closeWaiting();
            if (type != Constants.UPGRADE_FULL) {
                plus.nativeUI.alert('更新完成，即将重启应用', function () {
                    plus.runtime.restart()
                })
            }
        },
        function (e) {
            plus.nativeUI.closeWaiting()
            console.log('安装失败', e)
            let text = ''
            e?.message && (text = e.message)
            e?.code && (text += `[${e.code}]`)
            plus.nativeUI.alert('更新失败' + text)
        }
    )
}